/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { DeviceEventEmitter, EmitterSubscription, NativeEventEmitter, Platform } from 'react-native';
import NativeAvoidModule, { AvoidArea, AvoidAreaOptions, AvoidAreaType } from './turbo/NativeAvoidModule';

const AvoidUtil = NativeAvoidModule!;
const avoidAreaChangeEvent = 'avoidAreaChange';
let deEmitter: EmitterSubscription;
const IOS = 'ios'; //ios平台

let eventEmitter = {
    addListener: (_name: string, _fn: () => void): void => { },
    removeAllListeners: (_name: string): void => { },
};
// ios支持NativeEventEmitter，ohos和android支持DeviceEventEmitter
if (Platform.OS === IOS) {
    eventEmitter = new NativeEventEmitter(require('./turbo/NativeAvoidModule').default);
}

export const Avoid = {
  getWindowAvoidArea(type: AvoidAreaType): AvoidArea {
    return AvoidUtil.getWindowAvoidArea(type);
  },
  addAvoidAreaListener(cb: (avoidAreaOptions: AvoidAreaOptions) => void): void {
    AvoidUtil.addAvoidAreaListener();
    eventEmitter.addListener(avoidAreaChangeEvent, () => {
    });

    deEmitter = DeviceEventEmitter.addListener(avoidAreaChangeEvent, (avoidAreaOptions: AvoidAreaOptions) => {
      // ohos返回的数据类型是AvoidAreaOptions，iOS返回的数据是string类型
      if (typeof avoidAreaOptions === 'string') {
        avoidAreaOptions = JSON.parse(avoidAreaOptions);
      }
      cb(avoidAreaOptions);
    });
  },
  removeAvoidAreaListener(): void {
    AvoidUtil.removeAvoidAreaListener();
    if (eventEmitter) {
      eventEmitter.removeAllListeners(avoidAreaChangeEvent);
    }
    if (!deEmitter) {
      return;
    }
    deEmitter.remove();

  }
};

